package com.ecr.hub.util;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BundleUtils {

	public static Logger log = LoggerFactory.getLogger(BundleUtils.class);

	// Non synchronisé
	private static Map<String, ResourceBundle> bundleMap = new HashMap<String, ResourceBundle>();

	public static String getMessage(String cleBundle, String cleMessage) {
		return getMessage(cleBundle, cleMessage, null);
	}

	public static String getMessage(String cleBundle, String cleMessage,
			Object[] valeursCompl) {

		String message = null;
		try {
			ResourceBundle bundle = getBundle(cleBundle, getLocale());
			// En testant null on évite les problèmes du
			// "double-checked locking".
			message = (bundle != null) ? getMessage(bundle, cleMessage,
					valeursCompl) : getMessageNotFound(cleMessage);

		} catch (MissingResourceException e) {
			message = getMessageNotFound(cleMessage);
			log.warn(e.getMessage());
		}
		return message;
	}

	private static String getMessage(ResourceBundle bundle, String cleMessage,
			Object[] valeursCompl) throws MissingResourceException {

		String message = bundle.getString(cleMessage);
		if (valeursCompl != null) {
			MessageFormat formateur = new MessageFormat(message, getLocale());
			message = formateur.format(valeursCompl);
		}
		return message;
	}

	// Traitement Thread-safe (même si anti-pattern).
	private static ResourceBundle getBundle(String cleBundle, Locale locale)
			throws MissingResourceException {

		ResourceBundle bundle = (ResourceBundle) bundleMap.get(cleBundle);
		if (bundle == null) {
			synchronized (BundleUtils.class) {
				bundle = (ResourceBundle)bundleMap.get( cleBundle);
				if (bundle == null) {
					ClassLoader loader = getClassLoader();
					bundle = ResourceBundle
							.getBundle(cleBundle, locale, loader);
					bundleMap.put(cleBundle, bundle);
				}
			}
		}
		return bundle;
	}

	private static Locale getLocale() {
		FacesContext context = FacesContext.getCurrentInstance();
		UIViewRoot viewRoot = context.getViewRoot();
		Locale locale = null;
		if (viewRoot != null) {
			locale = viewRoot.getLocale();
		}
		if (locale == null) {
			locale = Locale.getDefault();
		}
		return locale;
	}

	private static ClassLoader getClassLoader() {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		if (loader == null) {
			loader = ClassLoader.getSystemClassLoader();
		}
		return loader;
	}

	private static String getMessageNotFound(String cleMessage) {

		StringBuffer msgBuff = new StringBuffer("???");
		msgBuff.append(cleMessage).append("???");
		return msgBuff.toString();
	}
}
